package com.aaa.config;

import com.alibaba.fastjson2.JSON;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 前后端分离时需要自定义成功处理类
 * 使用Response将处理结果输出位json字符串
 * */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Object principal=authentication.getPrincipal();//获得用户身份信息
        //Object credentials = authentication.getCredentials();//获得用户的凭证信息，比如密码
        //Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();//获取用户权限信息
        Map result=new HashMap<>();
        result.put("code",0);
        result.put("message","登录成功");
        result.put("data",principal);
        String json= JSON.toJSONString(result);//将对象的结果转换为json字符串

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
